﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Web;

namespace Webservice.Formatters
{
    public class CSVFormatter : BufferedMediaTypeFormatter
    {
        public CSVFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/comma-separated-values"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/csv"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/x-www-form-urlencoded"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
        }

        public override bool CanReadType(Type type)
        {
            return type == typeof(string);
        }

        public override bool CanWriteType(Type type)
        {
            return type == typeof(string);
        }

        public object ReadFromStream(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
        {
            Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);
            using (StreamReader sReader = new StreamReader(stream, effectiveEncoding))
            {
                return sReader.ReadToEnd();
            }
        }

        public void WriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders)
        {
            Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);
            using (StreamWriter sWriter = new StreamWriter(stream, effectiveEncoding))
            {
                sWriter.Write(value);
            }
        }
    }
}